package com.zhangh.summer.admin.support.exception;

import com.zhangh.summer.admin.support.base.JsonResponse;
import com.zhangh.summer.admin.support.boot.interfaces.OnAppConfigConditional;
import com.zhangh.summer.admin.support.boot.common.AppConfigEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by zhanghui on 2019-04-29.
 * restful controller 统一异常拦截处理
 */
@ControllerAdvice(annotations = {RestController.class})
@OnAppConfigConditional(AppConfigEnum.WEBMVC_CONFIGURATION_ENABLE)
@Slf4j
public class RestControllerExceptionHandler {

    @ExceptionHandler(value = NoHandlerFoundException.class)
    @ResponseBody
    public String defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception {
        String msg="找不到异常:"+e.getMessage()+",url:"+req.getRequestURI();
        log.error(msg);
        return new JsonResponse(false,404,msg).toJson();
    }

    @ExceptionHandler(RuntimeException.class)
    @ResponseBody
    public String handleRuntimeException(HttpServletRequest req, Exception e)throws Exception{
        String fullStackTrace= ExceptionUtils.getStackTrace(e);
        if(fullStackTrace.length()>1000){
            fullStackTrace = fullStackTrace.substring(0,1000)+"...";
        }

        String msg="服务端异常:\n \r"+fullStackTrace;//e.getMessage();
        log.error(msg);
        return new JsonResponse(false,500,msg).toJson();
    }


}
